from bs4 import BeautifulSoup

def calculate_net_short_position(html_content, futures_type):
    soup = BeautifulSoup(html_content, 'html.parser')
    total_buy_volume = 0
    total_sell_volume = 0

    # 找到所有合约相关的标题
    contract_headers = soup.find_all('a', {'data-bind': 'text:insShow'})
    for header in contract_headers:
        if futures_type in header.text:
            # 找到对应的表格
            table = header.find_next('table')
            if table:
                tbody = table.find('tbody')
                if tbody:
                    rows = tbody.find_all('tr')
                    for row in rows:
                        # 检查是否为合计行
                        if '合计' in ''.join([td.text.strip() for td in row.find_all('td')]):
                            try:
                                # 提取持买单量（第 7 列）
                                buy_volume_str = row.find_all('td')[6].text.strip()
                                buy_volume = int(buy_volume_str) if buy_volume_str.isdigit() else 0
                                total_buy_volume += buy_volume

                                # 提取持卖单量（第 10 列）
                                sell_volume_str = row.find_all('td')[10].text.strip()
                                sell_volume = int(sell_volume_str) if sell_volume_str.isdigit() else 0
                                total_sell_volume += sell_volume
                            except IndexError:
                                continue

    # 计算净空单
    net_short_position = total_sell_volume - total_buy_volume
    return net_short_position

# 读取 HTML 文件
with open('timeout_page_20250609.html', 'r', encoding='utf-8') as file:
    html_content = file.read()

# 示例调用
futures_type = 'IF'
net_short_position = calculate_net_short_position(html_content, futures_type)
print(f"{futures_type} 期货的净空单: {net_short_position}")